<?php
/**
 * Created by PhpStorm.
 * User: shwy
 * Date: 2017/5/18
 * Time: 16:06
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Base_Model extends CI_Model {

	protected $mTable;
	protected $mPkId = 'id';
	
	/**
	 * 功能: 配置数据库的名字
	 */
	public function __construct() {
		$sqlname = $this->config->item('aliyun')['sqlname'];

		$this->db = _getDb($sqlname);
	}

	// 数据库表名前缀
	public function prefix() {
		return $this->db->dbprefix;
	}
	
	// 
	public function table($table = '') {
		if (!$table) {
			$table = $this->mTable;
		}
		return $this->db->protect_identifiers($table, TRUE);
	}
	
	public function set_table($table) {
		$this->mTable = $table;
		return $this;
	}

	/**
	 * 插入数据
	 * @param array $data 要插入的数据
	 * @return mixed
	 */
	public function add($data) {
		return $this->db->insert($this->mTable, $data);

		return $this->db->last_query();
	}

	/**
	 * 插入数据返回自增长id
	 * @param array $data 要插入的数据
	 * @return int mixed 自增长id
	 */
	public function addId($data) {
		$this->db->insert($this->mTable, $data);

		return $this->db->insert_id();
	}

	/**
	 * 编辑数据
	 * @param array $data where条件
	 * @return int  bool   不等于0则表示更新成功
	 */
	public function edit($data, $arg) {

		$this->db->update($this->mTable, $data, $arg);

		return $this->db->affected_rows();
	}

	/**
	 * 某个字段加一
	 * @param array $arg
	 * @param array $stock[0] 要修改的字段名
	 * @param array $stock[1] where修改值如：stock = stock + 1
	 * @param array $stock[2] FALSE表示不转义，
	 * @return bool mixed
	 */
	public function setFieldChange($arg, $stock) {
		$this->db->where($arg);
		$this->db->set($stock[0], $stock[1], $stock[2]);
		$result = $this->db->update($this->mTable);

		__logInfo('商品出入库单sql修改', $this->db->last_query());

		return $result;
	}

	/**
	 * 删除数据
	 * @param array $data where条件
	 * @return mixed
	 */
	public function remove($data) {
		return $this->db->delete($this->mTable, $data);
	}

	/**
	 * 根据字段条件查询 一条/多条数据
	 * @param string $fields  查询字段
	 * @param array $arg  where参数
	 * @param int $isMore 0查询一条/1查询多条
	 * @return mixed
	 */
	public function getByFieldQueryData($fields = '*', $arg, $isMore = 0) {
		if ($isMore) {
			$result = $this->db->select($fields)
				->from($this->mTable)
				->where($arg)
				->get()
				->result_array();
			return $result;

		} else {
			$result = $this->db->select($fields)
				->from($this->mTable)
				->where($arg)
				->get()
				->row_array();
			return $result;
		}

//        return $this->db->last_query(); //打印sql语句
	}

	/**
	 * 自定义字段值 一条/多条数据
	 * @param string $fields  查询字段
	 * @param int $isMore 0查询一条/1查询多条
	 * @return mixed
	 */
	public function getData($fields = '*', $isMore = 0) {
		if ($isMore) {
			$result = $this->db->select($fields)
				->from($this->mTable)
				->get()
				->result_array();
			return $result;
		} else {
			$result = $this->db->select($fields)
				->from($this->mTable)
				->get()
				->row_array();
			return $result;
		}
	}
	
	/**
	 * 查询所有记录并模糊条件查询
	 * $this->db->where('字段名','字段值');
	 * $this->db->delete('表名');
	 * $this->db->update('表名');
	 * $where 判断是否启用where条件查询
	 */
	public function getDataSearch($fields = '*', $where, $searchArg) {
		if ($searchArg && $where) {
			$result = $this->db->select($fields)
				->from($this->mTable)
				->where($where)
				->like(
					$searchArg['field'],
					$searchArg['arg'],
					$searchArg['side']
				)
				->get()
				->result_array();

//            return $this->db->last_query();
			$result2[] = $result;

			$result2['total_num'] = count($this->db->select($fields)
					->from($this->mTable)
					->where($where)
					->like(
						$searchArg['field'],
						$searchArg['arg'],
						$searchArg['side']
					)
					->get()
					->result_array());

			return $result2;

		} else {
			$result = $this->db->select($fields)
				->from($this->mTable)
				->like(
					$searchArg['field'],
					$searchArg['arg'],
					$searchArg['side']
				)
				->get()
				->result_array();

			$result2['total_num'] = count($this->db->select($fields)
					->from($this->mTable)
					->like(
						$searchArg['field'],
						$searchArg['arg'],
						$searchArg['side']
					)
					->get()
					->result_array());

			$result2[] = $result;

			return $result2;

		}
	}

	/**
	 * 根据条件查询最大id
	 * @param string $fields  自定义查询字段
	 * @param $where array 查询条件
	 * @return mixed array  [id=>XX]
	 */
	public function getMaxId($fields = '*', $where) {
		return $this->db->select_max($fields)->from($this->mTable)->where($where)->get()->row_array();
	}

	/**
	 * 功能: 模糊条件查询
	 * 
	 * @param	$fields	查询字段
	 * @param	$where	查询条件
	 * @param	$$searchArg	like查询参数
	 * @param	$start_position 显示个数的起始位置
	 * @param	$pageSize 每页显示的个数
	 * 
	 * $this->db->where('字段名','字段值');
	 * $this->db->delete('表名');
	 * $this->db->update('表名');
	 * $where 判断是否启用where条件查询
	 */
	public function search($fields = '*', $where, $searchArg, $start_position, $pageSize) {
		// 如果有模糊查询参数 和 查询条件	
		// like()里面有三个参数. 字段, 关键字, 左右通配
		if ($searchArg && $where) {
			$result = $this->db->select($fields)
							   ->from($this->mTable)
							   ->where($where)
							   ->like(
									$searchArg['field'],
									$searchArg['arg'],
									$searchArg['side']
								)
							   ->limit($start_position, $pageSize)
							   ->get()
							   ->result_array();

//            return $this->db->last_query();
			$result2[] = $result;

			$result2['total_num'] = count($this->db->select($fields)
												   ->from($this->mTable)
												   ->where($where)
												   ->like(
														$searchArg['field'],
														$searchArg['arg'],
														$searchArg['side']
													)
												   ->get()
												   ->result_array()
										  );

			return $result2;
		// 否则没有where查询
		} else {
			$result = $this->db->select($fields)
							   ->from($this->mTable)
							   ->like(
									$searchArg['field'],
									$searchArg['arg'],
									$searchArg['side']
								)
							   ->limit($start_position, $pageSize)
							   ->get()
							   ->result_array();

			$result2['total_num'] = count($this->db->select($fields)
					->from($this->mTable)
					->like(
						$searchArg['field'],
						$searchArg['arg'],
						$searchArg['side']
					)
					->get()
					->result_array());

			$result2[] = $result;

			return $result2;

		}

//        return $this->db->last_query();

	}

	/**
	 * 分页函数
	 * @param string $tablename 表名
	 * @param string $per_nums  每页的数据量
	 * @param string $start_position    起始位置
	 * @param string $field    自定义字段名
	 * @return array
	 */
	public function page($tablename, $where, $per_nums, $start_position, $field = '*') {
		if ($where) {
			$this->db->select($field)->where($where)->order_by('id', 'DESC')->limit($per_nums, $start_position);
			$query = $this->db->get($tablename);
			$data  = $query->result_array();

			$data2['total_num'] = count($this->db->where($where)->get($tablename)->result_array());
			$data2[] = $data;
		} else {
			$this->db->select($field)->order_by('id', 'DESC')->limit($per_nums, $start_position);
			$query = $this->db->get($tablename);
			$data = $query->result_array();
			$data2['total_num'] = $this->db->count_all($tablename);
			$data2[] = $data;
		}

		return $data2;
	}

	/**
	 * find_in_set 查找
	 *
	 */
	public function FindInSetLimit($name, $per_nums, $start_position) {
//        $query = $this->db->query('SELECT `id`,`nickname` FROM ist_user where find_in_set("'.$name.'",role_id) limit '.$per_nums.','.$start_position.' ');
		$query = $this->db->query('SELECT `id`,`nickname` FROM ist_user where role_id like "%' . $name . '%" limit ' . $per_nums . ',' . $start_position . '');

		$data = $query->result();

		$data['total_num'] = count($this->db->query('SELECT * FROM ist_user where role_id like "%' . $name . '%"')->result_array());

//        return $this->db->last_query();

		return $data;
	}

	public function FindInSet($name) {
//        $query = $this->db->query('SELECT * FROM ist_user where find_in_set("'.$name.'",role_id)');
		$query = $this->db->query('SELECT * FROM ist_user WHERE role_id like "%' . $name . '%"');

//        return $this->db->last_query();

		return $query->result();
	}

	public function trans_begin() {
		return $this->db->trans_begin($this->mTable);
	}

	public function trans_status() {
		return $this->db->trans_status($this->mTable);
	}

	public function trans_rollback() {
		return $this->db->trans_rollback($this->mTable);
	}

	public function trans_commit() {
		return $this->db->trans_commit($this->mTable);
	}
	
//	------------------------------------------------------------------
	/**
	 * Writer: loseself
	 * Date: 2018.3.10
	 */
	
	// 增删改查
	 
	/**
	 * 功能: 根据条件查询数据, 获取结果
	 * 
	 * @param String $fields	查询字段
	 * @param String $where 	查询条件
	 * @param Bool   $bool 	        是否多条查询, 1多, 0少
	 */
	public function findData($fields, $where, $bool = 1) {
		// result_array(): 返回的是数组; result(): 返回的是对象	
		if ($bool) {
			$result = $this->db->select($fields)
							   ->from($this->mTable)
							   ->where($where)
							   ->get()
							   ->result_array();
		} else {
			$result = $this->db->select($fields)
							   ->from($this->mTable)
							   ->where($where)
							   ->get()
							   ->row_array();
		}
		return $result;
	}
	
	// 不加条件查询相应字段
	public function getArr($fields = '*', $perPage, $offset = 0) {
		$rowset = $this->db->select($fields)
						   ->from($this->mTable)
						   ->order_by('id', 'desc')
						   ->limit($perPage, $offset)
						   ->get()
						   ->result_array();
		return $rowset;
	}
	
	// 获得结果集的总个数
	public function getNum() 
	{
		$total = $this->db->count_all_results($this->mTable);
		return $total;
	}
	
	// 通过条件获得结果集的总个数
	public function getNumByArg($where) {
		$total = $this->db->where($where)->count_all_results($this->mTable);
		return $total;
	}
	
	
	// 设置分页
	public function links($url, $total, $perPage) 
	{
		$config['base_url'] 	= $url;
		$config['total_rows'] 	= $total;
		$config['page'] 		= $perPage;
		// $config['uri_segment']  = 4;
		$this->pagination->initialize($config);
		$links = $this->pagination->create_links();
		return $links;
	}
	
	// 更新
	public function update($data, $where) {
		return $this->db->update($this->mTable, $data, $where);
	}
	
	/**
	 * 分页函数
	 * 
	 * @param string $per_nums  每页的数据量
	 * @param string $start_position    起始位置
	 * @param string $field    自定义字段名
	 * @return array
	 */
	public function paging($fields = '*', $where, $per_nums, $start_position) {
		if (isset($where)) {		
			$data  = $this->db->select($fields)
						      ->from($this->mTable)
							  ->where($where)
						      ->order_by('id', 'desc')
						      ->limit($per_nums, $start_position)
						      ->get()
						      ->result_array();
		} else {
			$data  = $this->db->select($fields)
						      ->from($this->mTable)
						      ->order_by('id', 'desc')
						      ->limit($per_nums, $start_position)
						      ->get()
						      ->result_array();
		}
		$data['total_num'] = count($this->db->where($where)->get($this->mTable)->result_array());
		return $data;
	}

	/**
	 * 分页模糊查询函数
	 * 
	 * @param string $per_nums  每页的数据量
	 * @param string $start_position    起始位置
	 * @param string $field    自定义字段名
	 * @return array
	 */
	public function pagingLike($fields = '*', $where, $like, $per_nums, $start_position) {
		if (isset($where)) {		
			$data  = $this->db->select($fields)
						      ->from($this->mTable)
							  ->where($where)
							  ->like(
								     $like['field'],
							   	     $like['arg'],
									 $like['side']
								)
						      ->order_by('id', 'desc')
						      ->limit($per_nums, $start_position)
						      ->get()
						      ->result_array();
		} else {
			$data  = $this->db->select($fields)
						      ->from($this->mTable)
							  ->like(
								     $like['field'],
							   	     $like['arg'],
									 $like['side']
								)
						      ->order_by('id', 'desc')
						      ->limit($per_nums, $start_position)
						      ->get()
						      ->result_array();
		}
		$data['total_num'] = count($this->db->where($where)
											->like(
											     $like['field'],
										   	     $like['arg'],
												 $like['side']
											)
											->get($this->mTable)
											->result_array());
		return $data;
	}

	/**
	 * 功能: 模糊查询
	 * 
	 */
	public function findLike($fields = '*', $where, $searchArg, $more = 0)
	{
		if ($more) {
			$rowset = $this->db->select($fields)
						   ->from($this->mTable)
						   ->where($where)
						   ->like(
						     $searchArg['field'],
					   	     $searchArg['arg'],
							 $searchArg['side']
							)
						   ->get()
						   ->row_array();
		} else {
			$rowset = $this->db->select($fields)
						   ->from($this->mTable)
						   ->where($where)
						   ->like(
						     $searchArg['field'],
					   	     $searchArg['arg'],
							 $searchArg['side']
							)
						   ->get()
						   ->result_array();
		}
		return $rowset;
	}
	
	/**
	 * 分页函数
	 * 
	 * @param string $per_nums  每页的数据量
	 * @param string $start_position    起始位置
	 * @param string $field    自定义字段名
	 * @return array
	 */
	public function paginate($fields = '*', $where, $per_nums, $start_position) {
		if (isset($where)) {		
			$data  = $this->db->select($fields)
						      ->from($this->mTable)
							  ->where($where)
						      ->order_by('id', 'desc')
						      ->limit($per_nums, $start_position)
						      ->get()
						      ->result_array();
		} else {
			$data  = $this->db->select($fields)
						      ->from($this->mTable)
						      ->order_by('id', 'desc')
						      ->limit($per_nums, $start_position)
						      ->get()
						      ->result_array();
		}
		return $data;
	}
	
}
